package edu.notebook.controller;


import edu.notebook.controller.utils.R;
import edu.notebook.domain.User;
import edu.notebook.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public R getAll(){
        return new R(true, userService.getAll());
    }

    @PostMapping
    public R save(@RequestBody User user) throws IOException {
        System.out.println(user);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(new Date());
        user.setCreateTime(formattedDate);
        return new R(true,userService.saveUser(user));
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id){
        return new R(userService.delete(id));
    }

    @PutMapping
    public R update(@RequestBody User user){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(new Date());
        user.setUpdateTime(formattedDate);
        return new R(userService.update(user));
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id){
        return new R(true, userService.getById(id));
    }

    @GetMapping("/{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize){
        return new R(true, userService.getPage(currentPage, pageSize));
    }

    @GetMapping("/{username}/{password}")
    public R login(@PathVariable String username, @PathVariable String password){
        return new R(true ,userService.login(username, password));
    }

    @PutMapping("/{id}/{password}")
    public R updatepsw(@PathVariable String id, @PathVariable String password){
        return new R(true,userService.updatePassword(id, password));
    }


}
